/* RMI-C Server: Echo Sample (V1) */

#include "rmi.h"
#include "echo.h"

/* ************************ SERVANT ************************ */

struct echo_t {
  int cnt;
};

struct echo_t echo1;

char * message = "hello world";

void echo_hello_(void* this, void* in, void* out)
{
  struct echo_t * echo = (struct echo_t *)this;
  char ** msg = (char**)out;
  *msg = message;
  printf("echo->hello (call %d)\n", echo->cnt);
  echo->cnt++;  
}

void echo_sum_(void* this, void* in, void* out)
{
  struct echo_t * echo = (struct echo_t *)this;
  printf("echo->sum (call %d)\n", echo->cnt);
  struct two_int_t * xy = (struct two_int_t *)in;
  int * z = (int*)out;
  *z = xy->x + xy->y;
  echo->cnt++;  
}

void echo_goodbye_(void* this, void* in, void* out)
{
  struct echo_t * echo = (struct echo_t *)this;
  printf("echo->goodbye (call %d)\n", echo->cnt);
  char ** msg = (char**)in;
  printf("message = %s\n", *msg);  
  echo->cnt++;  
}

void echo_setperson_(void* this, void* in, void* out)
{
  struct echo_t * echo = (struct echo_t *)this;
  printf("echo->setperson (call %d)\n", echo->cnt);
  struct person_t * person = (struct person_t *)in;
  printf("person: %s %s\n",person->firstname, person->lastname);
  bool * test = (bool*)out;
  *test = true;
  echo->cnt++;  
}

void echo_testarray_(void* this, void* in, void* out)
{
  struct echo_t * echo = (struct echo_t *)this;
  printf("echo->testarray (call %d)\n", echo->cnt);
  xarray * xarrayin = (xarray*)in;
  printf("array[%d] = (", xarrayin->size);
  for(int i = 0 ; i < xarrayin->size; i++)
    printf("%d ", xarrayin->array[i]);
  printf("\b)\n");
  xarray * xarrayout = (xarray*)out;
  xarrayout->size = xarrayin->size;
  xarrayout->array = malloc(xarrayout->size*sizeof(int));
  for(int i = 0 ; i < xarrayout->size; i++)
    xarrayout->array[i] = xarrayout->size - i;
  echo->cnt++;  
}

/* ************************ SERVER ************************ */

int main(int argc, char* argv[])
{
  if( argc < 4){
    fprintf(stderr,"Usage: ./server <port> <naming-server host> <naming-server port>\n");
    exit(1);
  }
  int  port = atoi(argv[1]);
  char* naming_server_host = argv[2];
  int  naming_server_port = atoi(argv[3]);
  
  
  /* create server */
  SERVER * server = rmi_server_create(port);
  
  /* register methods */
  rmi_server_register_interface_echo(server);

  /* activate objects */
  rmi_server_activate_object(server, __echo__, 1, &echo1);
  
  /*binding objects*/
  rmi_serveur_bind(__echo__,"echo", naming_server_port, naming_server_host);

  /* start server */
  rmi_server_run(server);
  
}
